<?php

/**
 * NOTICE OF LICENSE
 *
 * THIS SOURCE FILE IS PART OF EVEBIT'S PRIVATE PROJECT.
 * 
 * DO NOT USE THIS FILE IN OTHER PLACE.
 *
 * @category    EveBit_Library
 * @package     Application
 * @author      Cheng Wei <berlios.o@gmail.com>
 * @version     $$Id: Default.php 130 2011-03-18 03:10:02Z cheng.wei $$
 * @copyright   Copyright (c) 2008 Evebit Inc. China (http://www.evebit.com)
 */

/**
 * Storage for authentication
 * 
 * @package     Application
 * @author      Cheng Wei <berlios.o@gmail.com>
 * @version     $$Id: Default.php 130 2011-03-18 03:10:02Z cheng.wei $$
 */
class Evebit_Auth_Storage_Default extends Zend_Auth_Storage_Session {
	
	/**
	 * @var object
	 */
	protected $_userInstance = null;
	
	/**
	 * @var string
	 */
	protected $_modelTypeClass = 'Varien_Object';
	
	/**
	 * Sets session storage options and initializes session namespace object
	 *
	 * @param  mixed $namespace
	 * @param  mixed $member
	 * @return void
	 */
	public function __construct($namespace = self::NAMESPACE_DEFAULT, $member = self::MEMBER_DEFAULT) {
		$this->_namespace = $namespace;
		$this->_member = $member;
		$this->_session = Evebit_Application::getSession();
	}
	
	/**
	 * @param string $type
	 */
	public function setModelTypeClass($type) {
		$this->_modelTypeClass = $type;
		return $this;
	}
	
	/**
	 * @return string
	 */
	public function getModelTypeClass() {
		return $this->_modelTypeClass;
	}
	
	/**
	 * Defined by Zend_Auth_Storage_Interface
	 *
	 * @return mixed
	 */
	public function read() {
		if ($this->_userInstance === null) {
			$type = $this->getModelTypeClass();
			$this->_userInstance = new $type();
			$userId = $this->_session->{$this->_member};
			if ($userId) {
				if (is_callable(array($this->_userInstance, 'load'))) {
					$this->_userInstance->load($userId);
				} elseif ($this->_userInstance instanceof Varien_Object) {
					$this->_userInstance->setId($userId);
				} elseif (is_callable(array($this->_userInstance, 'setId'))) {
					$this->_userInstance->setId($userId);
				} else {
					$this->_userInstance->id = $userId;
				}
			}
		}
		return $this->_userInstance;
	}

}

